﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using XData.Client.Components;

namespace XData.Client.Services
{
    public class AccountService
    {
        protected static List<ApiClient> Logined = new List<ApiClient>();

        protected ApiClient ApiClient = ApiClientManager.GetApiClient();

        // /User
        public bool Login(string userName, string password)
        {
            string relativeUri = "/User";
            bool rememberMe = false;
            bool result = ApiClient.Login(relativeUri, userName, password, rememberMe);
            if (result)
            {
                if (!Logined.Contains(ApiClient))
                {
                    Logined.Add(ApiClient);
                }
            }
            return result;
        }

        // /User
        public void Logout()
        {
            if (Logined.Contains(ApiClient))
            {
                string relativeUri = "/User";
                ApiClient.Logout(relativeUri);
                Logined.Remove(ApiClient);
            }
        }

        // /XData/Users
        public XElement GetUser(string userName)
        {
            string relativeUri = string.Format("/XData/Users?$filter=LoweredUserName eq '{0}'", userName);
            return ApiClient.Get(relativeUri).Elements().First();
        }

        // /User
        public bool ChangePassword(string oldPassword, string newPassword, string confirmPassword)
        {
            return ApiClient.ChangePassword("/User", oldPassword, newPassword, confirmPassword);
        }


    }
}
